<template>
  <view>
    <view class="TaskInfo" @touchmove.stop.prevent>
      <Hr-Pull-Load
        ref="hrPullLoad"
        :is-allow-pull="true"
        :height="-1"
        :bottom-tips="pullConfig.bottomTips"
        :lower-threshold="pullConfig.lowerThreshold"
        @loadMore="pullConfig.loadMore"
        @refresh="pullRefresh"
      >
        <view v-if="xzStatus === 2 || xzStatus === 5" class="task-info-xzstatus-img">
          <u-image v-if="xzStatus === 2" mode="widthFix" :src="implementStatus2" />
          <u-image v-else mode="widthFix" :src="implementStatus5" />
        </view>
        <Task-Cells
          v-if="task.taskList && task.taskList.length"
          hide-first-item-border-line
          class="taskinfo-list"
          :list="task.taskList"
        />
        <Task-Cells
          v-if="task.messageList && task.messageList.length"
          hide-first-item-border-line
          :list="task.messageList"
          :show-no-message="1"
          :row-pic-num="3"
          :pic-height="'100px'"
          @recallComment="recallComment"
          @videoView="videoView"
        />
        <u-modal
          v-model="recallCommentConnfig.show"
          :content="recallCommentConnfig.content"
          :title="recallCommentConnfig.title"
          :cancel-text="'取消'"
          show-cancel-button
          @confirm="startRecallComment"
        />
      </Hr-Pull-Load>
    </view>

    <view class="Task-Bottom">
      <view v-if="$store.state.task.townReject">
        <image :src="bottomBtnIcon[0]" class="Task-Bottom-icon" />
        <view @click="gotoTaskEnd">完成任务</view>
      </view>
      <view @click="comment.showCommentInput = true">
        <image :src="bottomBtnIcon[1]" class="Task-Bottom-icon" />
        <view>评论</view>
      </view>
    </view>
    <!-- 评论输入框 -->
    <u-popup
      v-model="comment.showCommentInput"
      safe-area-inset-bottom
      mode="top"
    >
      <Commom-Input
        ref="commentInput"
        :emit-close="true"
        :input-call-back="submitComment"
        :inpit-height="370"
        @close="comment.showCommentInput = false"
      />
    </u-popup>

    <u-mask
      :mask-click-able="false"
      :show="videoMask.show"
      @click="videoMask.show = false"
    >
      <view class="video-view-content">
        <view class="playerClose">
          <u-icon
            class="close-icon"
            name="plus-circle"
            color="#fff"
            size="48"
            @click="closeVideo"
          />
        </view>

        <view
          v-show="videoMask.show"
          ref="videoboxshowTaskCells"
          class="videoboxshowTaskCells"
        />
      </view>
    </u-mask>
  </view>
</template>

<script type="text/ecmascript-6">
/* eslint-disable no-undef */

import TaskCells from './components/TaskCells';
import { conversionBase64 } from '@/utils/utils';
import { downFileServer } from '@/utils/files';
import { mapState } from 'vuex';
import { addComment, updCommentStatus } from '@/api/task/taskDetail';
import CommomInput from '@/common/commentInput/CommentInput';
import DPlayer from 'dplayer';

export default {
  components: {
    TaskCells,
    CommomInput
  },

  inject: ['connectStore'],

  data() {
    return {
      // showFinishBtn: false,
      fileType: 'Y0012',
      bottomBtnIcon: [require('@/static/img/task/taskfinish.png'), require('@/static/img/task/taskreview.png')],
      // pullscroll
      pullConfig: {
        // 加载更多时的底部提示，‘nomore’：没有更多数据了；‘loading’：加载中...；‘more’：上拉加载更多；
        bottomTips: 'more',
        lowerThreshold: 10, // 距离组件底部多远时触发加载更多
        loadMore: this.loadMore
      },

      // 评论
      comment: {
        inpitHeight: 370,
        showCommentInput: false,
        commentInputMaxLength: 240,
        content: '',
        commentInputStyle: {
          'padding': '12px'
        },
        takePhotoConfig: {
          maxSize: 1024 * 1024 * 12, // 12mb
          fileList: [],
          sourceType: ['camera'] // ['album', 'camera']
        }
      },

      // 撤回
      recallCommentConnfig: {
        show: false,
        content: '是否确认撤回该评论？',
        title: '确认撤回',
        request: {}
      },

      // 乡镇被驳回
      // townReject: false,
      detailsOne: {},

      videoMask: {
        show: false,
        dp: {}
      },

      xzStatus: undefined,
      implementStatus5: require('@/static/img/task/implementStatus5.svg'),
      implementStatus2: require('@/static/img/task/implementStatus2.svg')
    };
  },

  computed: {
    ...mapState(['task'])
  },

  created() {
    const { status, autoLoad } = this.$route.query;
    this.xzStatus = Number(status);
    if (autoLoad === '1') {
      this.pullRefresh();
    }

    this.afterResponse();
  },

  methods: {
    // 请求完评论执行
    afterResponse() {
      setTimeout(() => {
        const len = this.$store.getters.getter['task/msgLength'];
        if (len < 2) {
          this.pullConfig.bottomTips = '';
        }
      }, 200);
    },

    // 关闭视频
    closeVideo() {
      this.videoMask.show = false;
      this.videoMask.dp.destroy && this.videoMask.dp.destroy();
    },
    // 预览视频
    videoView(file) {
      // !way 1
      /* this.videoMask.show = true;
      setTimeout(() => {
        const el = this.$refs.videoboxshowTaskCells.$el;
        const dp = new DPlayer({
          container: el,
          autoplay: true,
          loop: true,
          video: {
            url: file.img
          }
        });

        this.videoMask.dp = dp;
      }, 500); */

      //! way2
      /* uni.showLoading({
        title: '视频加载中'
      });
      downFileServer(file.img).then(res => {
        uni.hideLoading();
        const blob = res.data;
        const url = window.URL.createObjectURL(blob);
        this.videoMask.show = true;

        setTimeout(() => {
          const el = this.$refs.videoboxshowTaskCells.$el;
          const dp = new DPlayer({
            container: el,
            autoplay: true,
            loop: true,
            video: {
              url
            }
          });

          this.videoMask.dp = dp;
        }, 500);
      }); */

      //! way3
      uni.showLoading({
        title: '视频加载中'
      });
      downFileServer(file.img).then(res => {
        uni.hideLoading();
        const blob = res.data;
        const url = window.URL.createObjectURL(blob);
        this.videoMask.show = true;

        setTimeout(() => {
          const el = this.$refs.videoboxshowTaskCells.$el;
          const dp = new DPlayer({
            container: el,
            autoplay: true,
            loop: true,
            video: {
              url
            }
          });

          this.videoMask.dp = dp;
        }, 500);
      });
      console.log(file);
    },

    pullRefresh(reloadType) {
      const query = this.$route.query;
      this.pullConfig.bottomTips = 'more';
      const xzRole = !!this.xzStatus;
      this.$store.dispatch('task/getTaskDetail', {
        taskGuid: query.guid,
        programGuid: query.programGuid,
        action: this.hrPullReset,
        xzRole,
        status: this.xzStatus,
        enterpriseCode: query.enterpriseCode,
        reloadType
      });
    },

    // 确认完成按钮
    gotoTaskEnd() {
      const { status, detailTaskGuid, cEnterpriseName } = this.$store.state.task.detailsOne;
      const query = this.$route.query;
      this.$router.push({
        path: '/taskdetail/taskend',
        query: {
          ...query,
          cEnterpriseName,
          status,
          detailTaskGuid,
          taskGuid: this.$store.state.task.resData.guid
        }
      });
    },

    // 判断乡镇是否是被驳回
    // getTownReject(data) {
    //   const appRole = uni.getStorageSync('appRole');
    //   const userId = uni.getStorageSync('userId');
    //   if (appRole && appRole.includes('乡镇')) {
    //     console.log(data);
    //     const details = data.data.details;
    //     bbq:
    //     for (let i = 0; i < details.length; i++) {
    //       for (let j = 0; j < details[i].users.length; j++) {
    //         if (details[i].users[j].userId === userId || details[i].users[j].isCheck === 1) {
    //           this.detailsOne = details[i];
    //           break bbq;
    //         }
    //       }
    //     }
    //     console.log(this.detailsOne);
    //     if (Number(this.detailsOne.status) === 5) {
    //       this.townReject = true;
    //     }
    //   }
    // },
    hrPullReset(res, type) {
      // if (type === '明细') {
      //   this.getTownReject(res);
      // }

      if (type === '评论') {
        if (res.total <= this.task.commentConfig.pageSize) {
          this.$store.commit('task/commentConfigNomore');
          this.pullConfig.bottomTips = 'nomore';
          this.afterResponse();
        }
      }
      setTimeout(() => {
        this.$refs.hrPullLoad.reSet();
      }, 300);
    },

    // 开始撤回
    startRecallComment() {
      updCommentStatus(this.recallCommentConnfig.request).then(res => {
        uni.showToast({
          title: res.message,
          duration: 1500
        });
        if (res.success) {
          this.$store.commit('task/delMessage', this.recallCommentConnfig.request.index);
        }
      });
    },
    // 撤回
    recallComment({ item, index }) {
      const requestData = {
        guid: item.cardMsg.guid,
        'status': -1,
        index
      };

      this.recallCommentConnfig.request = requestData;
      this.recallCommentConnfig.show = true;
    },

    loadMore() {
      if (this.pullConfig.bottomTips === 'loading' || this.pullConfig.bottomTips === 'nomore') {
        return;
      }
      const taskGuid = this.$route.query.guid;
      const action = (res, type) => {
        if (res.isNext) {
          this.pullConfig.bottomTips = 'more';
        } else {
          this.pullConfig.bottomTips = 'nomore';
        }
      };
      this.pullConfig.bottomTips = 'loading';
      this.$store.dispatch('task/getListComment', { taskGuid, action });
    },

    getUpload() {
      return this.$refs.uUpload;
    },

    // 相机打开还是相册打开
    takePhotoByCamera(type) {
      const el = this.getUpload().$children[0].$children[0].$el;
      this.comment.takePhotoConfig.sourceType.splice(0, 1, type);
      el.click();
    },

    choosePhoto(fileList) {
      const files = fileList.map((file, index) => {
        return {
          index,
          file: file.file
        };
      });

      files.forEach(async(file, i) => {
        file.b64 = await conversionBase64(file.file);
        if (i === files.length - 1) {
          this.comment.takePhotoConfig.fileList = files;
        }
      });
    },

    removeTackedPhoto(img, i) {
      this.getUpload().remove(i);
      this.comment.takePhotoConfig.fileList.splice(i, 1);
    },

    // 提交评论
    submitComment(comment) {
      const query = this.$route.query;
      const { guid: taskGuid } = query;
      const { content, files } = comment;
      const enterpriseCode = this.$store.state.task.enterpriseGuid;
      const editUser = uni.getStorageSync('userId');
      let requestForm = null;
      const requestData = {
        taskGuid,
        content,
        type: this.fileType,
        enterpriseCode,
        editUser,
        files
      };

      const headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
      };

      requestForm = new FormData();
      for (const key in requestData) {
        if (key !== 'files') {
          requestForm.append(key, requestData[key]);
        }
      }

      if (files.length) {
        headers['Content-Type'] = 'multipart/form-data';
        files.forEach(file => {
          requestForm.append('files', file.file);
        });
      }
      uni.showLoading({
        title: '提交中'
      });
      addComment(requestForm, headers).then(res => {
        uni.showToast({
          title: res.message,
          duration: 2000,
          icon: 'none'
        });
        if (res.success) {
          this.comment.showCommentInput = false;
          // this.$refs.commentInput.clearData();
          // this.$store.commit('task/addComment', requestData);
          this.pullRefresh('refreshMsgOnly');
        }
      });
    }

  }

};
</script>

<style lang="scss" scoped>
.TaskInfo {
  height: calc(100vh - 55px);
  overflow: scroll;
  .taskinfo-list {
    &::after {
      content: '';
      height: 10px;
      display: block;
    }
  }
  .task-info-xzstatus-img{
    width: 91px;
    height: 86px;
    position: absolute;
    z-index: 9999;
    right: 12px;
    top: 14px;
  }
}

.Task-Bottom {
  display: flex;
  background-color: #fff;
  height: 55px;
  border-top: 1px solid #ebeef5;
  font-size: 17px;
  color: #303133;

  > view {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 7px 0;

    &:first-child {
      border-right: 1px solid #d8d8d8;
    }
    .Task-Bottom-icon {
      width: 17px;
      height: 17px;
      margin-right: 8px;
    }
  }
}

.task-comment-input {
  margin: 12px 8px;
  background-color: #EAECF0;
  border-radius: 14px;
  .task-comment-img-view {
    padding: 12px 8px;;
    min-height: 30px;
    display: grid;
    gap: 10px 13px;
    grid-template-columns: repeat(auto-fill, minmax(44px, 1fr));
    > view {
      height: 44px;
    }

    .task-comment-img-content {
      position: relative;
      .task-comment-img-close {
        position: absolute;
        right: -5px;
        top: -5px;
        z-index: 12;
        background-color: red;
        border-radius: 60px;
      }
    }
  }
}

.task-comment-footer {
    display: flex;
    justify-content: space-between;
    padding: 0 24px;
    .task-comment-footer-camera {
      margin-right: 24px;
    }

    .task-submitComment {
      color: #2979FF;
      font-weight: 600;
    }
  }

  .video-view-content {
  width: 100%;
  height: 100%;
  background-color: black;
  .playerClose {
    text-align: right;
    padding: 5px;
    .close-icon {
      transform: rotate(45deg);
    }
  }

  .videoboxshowTaskCells {
    width: 100%;
    height: calc(100% - 35px);
  }

}
</style>
